package com.example.spzx;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.example.spzx.model.entity.system.SysUser;
import com.example.spzx.model.vo.common.Result;
import com.example.spzx.model.vo.common.ResultCodeEnum;
import com.example.utils.AuthContextUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

public class LoginAuthInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,Object handler) throws Exception{
        String method=httpServletRequest.getMethod();
        if("OPTIONS".equals(method)){
            return true;
        }
        String token=httpServletRequest.getHeader("token");
        if(StrUtil.isEmpty(token)){
            responseNoLoginInfo(httpServletResponse);
            return false;
        }
        String sysUserInfoJson=stringRedisTemplate.opsForValue().get("user:login"+token);
        if(StrUtil.isEmpty(sysUserInfoJson)){
            responseNoLoginInfo(httpServletResponse);
            return false;
        }
        SysUser sysUser=JSON.parseObject(sysUserInfoJson,SysUser.class);
        AuthContextUtil.set(sysUser);
        stringRedisTemplate.expire("user:login"+token,30, TimeUnit.MINUTES);
     return true;
    }
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();  // 移除threadLocal中的数据
    }
}
